using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

using phorm.database.core;

namespace phorm.model.fields
{
    /// <summary>
    /// A MD5 password based Varchar that is compatible with PHP
    /// </summary>
    public class MD5Password : Varchar
    {
        /// <summary>
        /// Constant default length of this column
        /// </summary>
        const int DEFAULT_LENGTH = 32;

        /// <summary>
        /// Constructor utilizes base constructor for initialization.
        /// </summary>
        /// <param name="obj">The model object to which this column belongs</param>
        public MD5Password(DatabaseRecord obj)
            : base(obj, MD5Password.DEFAULT_LENGTH)
        {
        }

        /// <summary>
        /// Accessor methods for setting and getting the value of this column.
        /// </summary>
        new public string value
        {
            get
            {
                return this._value.ToString();
            }
            set
            {
                // http://www.codeproject.com/dotnet/MD5FunctionPHP.asp
                MD5 md5          = MD5CryptoServiceProvider.Create();
                byte[] dataMd5   = md5.ComputeHash(Encoding.Default.GetBytes(value));

                // Convert each byte in the array into a hexadecimal character to appedn to the string builder.
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < dataMd5.Length; i++)
                    sb.AppendFormat("{0:x2}", dataMd5[i]);

                this._value =  sb.ToString();
            }
        }
    }
}
